/* Copyright (c) 2007 Scott Lembcke
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>

#include "chipmunk.h"
#include "prime.h"

static cpHandle*
cpHandleAlloc(void)
{
	return malloc(sizeof(cpHandle));
}

static cpHandle*
cpHandleInit(cpHandle *hand, void *obj)
{
	hand->obj = obj;
	hand->retain = 0;
	hand->stamp = 0;
	
	return hand;
}

static cpHandle*
cpHandleNew(void *obj)
{
	return cpHandleInit(cpHandleAlloc(), obj);
}

static inline void
cpHandleRetain(cpHandle *hand)
{
	hand->retain++;
}

static inline void
cpHandleFree(cpHandle *hand)
{
	free(hand);
}

static inline void
cpHandleRelease(cpHandle *hand)
{
	hand->retain--;
	if(hand->retain == 0)
		cpHandleFree(hand);
}


cpSpaceHash*
cpSpaceHashAlloc(void)
{
	return calloc(1, sizeof(cpSpaceHash));
}

static void
cpSpaceHashAllocCells(cpSpaceHash *hash, int num)
{
	free(hash->cells);
	hash->cells = (cpSpaceHashBin **)calloc(num, sizeof(cpSpaceHashBin *));
}

static int
handleSetEql(void *obj, void *elt)
{
	cpHandle *hand = elt;
	return (obj == hand->obj);
}

static void *
handleSetTrans(void *obj, void *unused)
{
	cpHandle *hand = cpHandleNew(obj);
	cpHandleRetain(hand);
	
	return hand;
}

cpSpaceHash*
cpSpaceHashInit(cpSpaceHash *hash, float celldim, int cells, cpSpaceHashBBFunc bbfunc)
{
	hash->size = next_prime(cells);
	hash->celldim = celldim;
	hash->bbfunc = bbfunc;
	
	cpSpaceHashAllocCells(hash, hash->size);
	hash->bins = NULL;
	hash->handleSet = cpHashSetNew(0, &handleSetEql, &handleSetTrans);
	
	hash->stamp = 1;
	
	return hash;
}

cpSpaceHash*
cpSpaceHashNew(float celldim, int cells, cpSpaceHashBBFunc bbfunc)
{
	return cpSpaceHashInit(cpSpaceHashAlloc(), celldim, cells, bbfunc);
}

static inline void
clearHashCell(cpSpaceHash *hash, int index)
{
	cpSpaceHashBin *bin = hash->cells[index];
	while(bin){
		cpSpaceHashBin *next = bin->next;
		
		cpHandleRelease(bin->handle);
		bin->next = hash->bins;
		hash->bins = bin;
		
		bin = next;
	}
	
	hash->cells[index] = NULL;
}

static void
clearHash(cpSpaceHash *hash)
{
	int i;
	for(i=0; i<hash->size; i++)
		clearHashCell(hash, i);
}

static void
freeBins(cpSpaceHash *hash)
{
	cpSpaceHashBin *bin = hash->bins;
	while(bin){
		cpSpaceHashBin *next = bin->next;
		free(bin);
		bin = next;
	}
}

static void
handleFreeWrap(void *elt, void *unused)
{
	cpHandle *hand = elt;
	cpHandleFree(hand);
}

void
cpSpaceHashDestroy(cpSpaceHash *hash)
{
	clearHash(hash);
	freeBins(hash);
	
	cpHashSetEach(hash->handleSet, &handleFreeWrap, NULL);
	cpHashSetFree(hash->handleSet);
	
	free(hash->cells);
}

void
cpSpaceHashFree(cpSpaceHash *hash)
{
	if(!hash) return;
	cpSpaceHashDestroy(hash);
	free(hash);
}

void
cpSpaceHashResize(cpSpaceHash *hash, float celldim, int cells)
{
	clearHash(hash);
	
	hash->celldim = celldim;
	hash->size = next_prime(cells);
	
	cpSpaceHashAllocCells(hash, hash->size);
}

static inline int
containsHandle(cpSpaceHashBin *bin, cpHandle *hand)
{
	while(bin){
		if(bin->handle == hand) return 1;
		bin = bin->next;
	}
	
	return 0;
}

static inline cpSpaceHashBin *
getEmptyBin(cpSpaceHash *hash)
{
	cpSpaceHashBin *bin = hash->bins;
	if(!bin)
		return malloc(sizeof(cpSpaceHashBin));

	hash->bins = bin->next;
	return bin;
}

#define hash_func(x, y, n) \
	(((unsigned long) (x))*2185031351ul ^ \
	 ((unsigned long) (y))*4232417593ul)% \
	((unsigned long) (n))

static inline void
hashHandle(cpSpaceHash *hash, cpHandle *hand, cpBB bb)
{
	float dim = hash->celldim;
	int l = bb.l/dim;
	int r = bb.r/dim;
	int b = bb.b/dim;
	int t = bb.t/dim;
	
	int n = hash->size;
	int i,j;
	for(i=l; i<=r; i++){
		for(j=b; j<=t; j++){
			int index = hash_func(i,j,n);
			cpSpaceHashBin *bin = hash->cells[index];
			
			if(containsHandle(bin, hand)) continue;

			cpHandleRetain(hand);
			cpSpaceHashBin *newBin = getEmptyBin(hash);
			newBin->handle = hand;
			newBin->next = bin;
			hash->cells[index] = newBin;
		}
	}
}

void
cpSpaceHashInsert(cpSpaceHash *hash, void *obj, unsigned long id, cpBB bb)
{
	cpHandle *hand = cpHashSetInsert(hash->handleSet, id, obj, NULL);
	hashHandle(hash, hand, bb);
}

void
cpSpaceHashRehashObject(cpSpaceHash *hash, void *obj, unsigned long id)
{
	cpHandle *hand = cpHashSetFind(hash->handleSet, id, obj);
	hashHandle(hash, hand, hash->bbfunc(obj));
}

void
handleRehashHelper(void *elt, void *data)
{
	cpHandle *hand = elt;
	cpSpaceHash *hash = data;
	
	hashHandle(hash, hand, hash->bbfunc(hand->obj));
}

void
cpSpaceHashRehash(cpSpaceHash *hash)
{
	clearHash(hash);
	
	cpHashSetEach(hash->handleSet, &handleRehashHelper, hash);
}

void
cpSpaceHashRemove(cpSpaceHash *hash, void *obj, unsigned long id)
{
	cpHandle *hand = cpHashSetRemove(hash->handleSet, id, obj);
	hand->obj = NULL;
	cpHandleRelease(hand);
}

typedef struct eachPair {
	cpSpaceHashIterator func;
	void *data;
} eachPair;

void
eachHelper(void *elt, void *data)
{
	cpHandle *hand = elt;
	
	eachPair *pair = data;
	pair->func(hand->obj, pair->data);
}

void
cpSpaceHashEach(cpSpaceHash *hash, cpSpaceHashIterator func, void *data)
{
	eachPair pair = {func, data};
	cpHashSetEach(hash->handleSet, &eachHelper, &pair);
}

static inline void
query(cpSpaceHash *hash, cpSpaceHashBin *bin, void *obj, cpSpaceHashQueryFunc func, void *data)
{
	for(; bin; bin = bin->next){
		cpHandle *hand = bin->handle;
		void *other = hand->obj;
		
		if(hand->stamp == hash->stamp || obj == other || !other) continue;
		
		func(obj, other, data);
		hand->stamp = hash->stamp;
	}
}

void
cpSpaceHashQuery(cpSpaceHash *hash, void *obj, cpBB bb, cpSpaceHashQueryFunc func, void *data)
{	
	float dim = hash->celldim;
	int l = bb.l/dim;
	int r = bb.r/dim;
	int b = bb.b/dim;
	int t = bb.t/dim;
	int n = hash->size;
	
	int i,j;
	for(i=l; i<=r; i++){
		for(j=b; j<=t; j++){
			int index = hash_func(i,j,n);
			query(hash, hash->cells[index], obj, func, data);
		}
	}
	
	hash->stamp++;
}

typedef struct queryRehashPair {
	cpSpaceHash *hash;
	cpSpaceHashQueryFunc func;
	void *data;
} queryRehashPair;

static void
handleQueryRehashHelper(void *elt, void *data)
{
	cpHandle *hand = elt;
	
	queryRehashPair *pair = data;
	cpSpaceHash *hash = pair->hash;
	cpSpaceHashQueryFunc func = pair->func;

	float dim = hash->celldim;
	int n = hash->size;

	void *obj = hand->obj;
	cpBB bb = hash->bbfunc(obj);

	int l = bb.l/dim;
	int r = bb.r/dim;
	int b = bb.b/dim;
	int t = bb.t/dim;

	int i,j;
	for(i=l; i<=r; i++){
		for(j=b; j<=t; j++){
			int index = hash_func(i,j,n);
			cpSpaceHashBin *bin = hash->cells[index];
			
			if(containsHandle(bin, hand)) continue;
			query(hash, bin, obj, func, pair->data);
			
			cpHandleRetain(hand);
			cpSpaceHashBin *newBin = getEmptyBin(hash);
			newBin->handle = hand;
			newBin->next = bin;
			hash->cells[index] = newBin;
		}
	}
	
	hash->stamp++;
}

void
cpSpaceHashQueryRehash(cpSpaceHash *hash, cpSpaceHashQueryFunc func, void *data)
{
	clearHash(hash);

	queryRehashPair pair = {hash, func, data};
	cpHashSetEach(hash->handleSet, &handleQueryRehashHelper, &pair);
}
